//
//  SocketManager.m
//  Proto
//
//  Created by kingly on 15/11/23.
//  Copyright © 2015年 Will. All rights reserved.
//

#import "SocketManager.h"
#import "GCDAsyncSocket.h"

#define SOCKET_TIME_OUT -1

@interface SocketManager () <GCDAsyncSocketDelegate>{
    GCDAsyncSocket* socket;

}
@end

@implementation SocketManager

#pragma mark - initialization
static SocketManager* instance = nil;
static dispatch_once_t onceToken;
+(SocketManager*)getInstance
{
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

- (id) copyWithZone:(NSZone*)zone
{
    return self;
}

-(id)init
{
    if(self = [super init])
    {
        if(socket == nil)
        {
            //初始化socket
           
        }
    }
    return self;
}


/**
 * 创建 socket连接
 */
- (void)connectToUrl:(NSURL *)url;
{
    NSError *error = nil;
    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    if (![socket connectToUrl:url withTimeout:-1 error:&error]) {
        if (_myDelegate && [_myDelegate respondsToSelector:@selector(socketDidDisconnectWithError:)]) {
            [_myDelegate socketDidDisconnectWithError:error];
        }
    }
}
/**
 *  发送数据
 *
 *  @param prot 协议信息
 *  @param data 封装的数据
 */
- (void) sendContent:(DataPacket* )dataPacket{
    
    [socket writeData:[dataPacket requestDataToByteStream] withTimeout:SOCKET_TIME_OUT tag:0];
    [socket readDataWithTimeout:SOCKET_TIME_OUT tag:0];
}

#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToUrl:(NSURL *)url;
{
    NSLog(@"[socket] Connected to %@", url);
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)socket withError:(NSError *)error;
{
    if (_myDelegate && [_myDelegate respondsToSelector:@selector(socketDidDisconnectWithError:)]) {
        [_myDelegate socketDidDisconnectWithError:error];
    }
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
{
    TakePacket *takePacket   = [[TakePacket alloc] init];
    takePacket.receivedData  = data;
    takePacket.protoData = [takePacket takeDataToByteStream];
    if (_myDelegate && [_myDelegate respondsToSelector:@selector(socketDidReadData:)]) {
        [_myDelegate socketDidReadData:takePacket.protoData];
    }
    [sock readDataWithTimeout:-1 tag:0];
    
}



@end
